package cn.baiweigang.uu.service.fetch;

import cn.baiweigang.uu.GlobalContext;
import cn.baiweigang.uu.db.dataobj.StockInfoDo;
import cn.baiweigang.uu.utils.DateUtil;
import cn.baiweigang.uu.utils.StringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class MaiRuiService extends FetchBaseService {
    private static String CN_LIST = "http://api.mairui.club/hslt/list/";
    private static String HK_LIST = "http://api.mairui.club/hk/list/";

    public void pullStockBaseInfo() {
        //获取沪深
        JSONArray cn = pull(CN_LIST, null);
        //获取港股
        JSONArray hk = pull(HK_LIST, null);
        //保存到DB
        saveBaseInfo2Db(cn);
        saveBaseInfo2Db(hk);
    }

    private void saveBaseInfo2Db(JSONArray data) {
        String ds = DateUtil.getDs();
        List<StockInfoDo> stockInfoDoList = new ArrayList<>();
        if (data != null && data.size() > 0) {
            for (int i = 0; i < data.size(); i++) {
                JSONObject jsonObject = data.getJSONObject(i);
                StockInfoDo stockInfoDo = new StockInfoDo();
                stockInfoDo.setDm(jsonObject.getString("dm"));
                stockInfoDo.setJys(jsonObject.getString("jys"));
                stockInfoDo.setMc(jsonObject.getString("mc"));
                stockInfoDo.setDs(ds);
                stockInfoDoList.add(stockInfoDo);
            }
            baseInfoRepository.insertOrUpdateBatch(stockInfoDoList);
        }
    }

    private JSONArray pull(String api, String urlParam) {
        String url;
        if (StringUtil.isNotBlank(urlParam)) {
            url = api + urlParam;
        } else {
            url = api + GlobalContext.dbConfigCache.get("mairui_licence");
        }
        String resp = httpService.doGet(url, null, null);
        if (StringUtil.isNotBlank(resp)) {
            return JSONArray.parseArray(resp);
        }

        return null;
    }
}
